const Service = require('egg').Service;
const _ = require('lodash')

class AppService extends Service {

    //管理员登录，直接通过手机号登录就行
    async findOne(where) {
        const { app: { model: { User } } } = this
        let user = await User.findOne({
            where,
            raw: true
        })
        return user
    }

    //查询用户角色权限数据
    async getUserPower(where) {
        const { app: { model: { User, Role, RolePower } } } = this

        let user = await Role.findOne({
            attributes: ['id', 'role_name'],
            include: [
                {
                    attributes: ['power_code', 'power_text'],
                    model: RolePower,
                    require: false,
                },
                {
                    attributes: ['avatar', 'name'],
                    model: User,
                    require: true,
                    where,
                }
            ],
        })
        return user
    }

    //查询用户列表
    async index(where) {
        const { app: { model: { User, Role } } } = this

        let user = await User.findAndCountAll({
            attributes: ['userid', 'mobile', 'name', 'position', 'email', 'role_id', 'department'],
            include: [
                {
                    attributes: ['role_name'],
                    model: Role,
                    require: true,
                }
            ],
            raw: true,
            where,
        })
        return user
    }

    //设置用户角色
    async setRole({ department, userid }) {
        const { app: { model: { User, Role } } } = this
        let user = await User.update({
            department
        }, {
                where: { userid }
            })
        return user
    }

    //获取下级用户
    async getChildUser() {
        const { app, app: { model: { User } } } = this

        //查询所有部门
        let all_dept = await this.app.model.Dept.findAll()

        //获取下级部门
        let child_dept = []

        let lookfor = (arr, pid) => {
            for (var a of arr) {
                if (a.id != pid && a.parentid == pid) {
                    if (_.indexOf(child_dept, a.id) == -1) {
                        child_dept.push(a.id)
                    }
                    lookfor(arr, a.id)
                }
            }
        }

        let user_depts = this.ctx.state.user.department.split(',')

        for (let _deptId of user_depts) {
            child_dept.push(_deptId)
            lookfor(all_dept, _deptId)
        }

        //查询用户
        let child_user_entity = await User.findAll({
            where: {
                department: {
                    $in: child_dept
                }
            },
            raw: true
        })

        return child_user_entity
    }
}
module.exports = AppService
